//
//  ZYCTeachingTeachLearningPaperViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/2.
//

#import "ZYCTeachingTeachLearningPaperViewController.h"
#import "ZYCTeachLearningPaperModel.h"
#import "ZYCTeachingTeachLearningDetailHeaderView.h"
#import "ZYCTeachingTeachLearningPaperCell.h"
#import "ZYCTeachingTeachLearningPaperContentCell.h"
#import "ZYCTeachLearningSubmitModel.h"
#import "ZYCTeachLearningLocalDataManager.h"
#import "ZYCUserLoginModel.h"
#import "NSString+BTExtension.h"
#import "ZYCMessageRevokeView.h"

@interface ZYCTeachingTeachLearningPaperViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UIButton *rightButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZYCTeachLearningPaperModel *paperModel;
@property (nonatomic, strong) ZYCTeachingTeachLearningDetailHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *selectResultArr;
@property (nonatomic, strong) NSArray *localSaveArr;
@property (nonatomic, strong) ZYCMessageRevokeView *revokeView;


@end

@implementation ZYCTeachingTeachLearningPaperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self createCurrentPaperFilePath];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.localSaveArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        [self.selectResultArr addObjectsFromArray:self.localSaveArr];
//        NSLog(@"解档:%@",self.localSaveArr);
    }
    self.title = @"详情";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    [self.headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.tableView);
        make.width.mas_equalTo(kScreenWidth);
    }];
    [self.tableView layoutIfNeeded];
    [self loadTeachLearningPaper];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.paperModel.subjectVoList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCSubjectModel *model = self.paperModel.subjectVoList[indexPath.section];
    if ([model.subjectType integerValue] == 3) {//简答题
        ZYCTeachingTeachLearningPaperContentCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeachingTeachLearningPaperContentCell class])];
        cell.model = model;
        cell.selectModelBlock = ^(ZYCSubjectModel * _Nonnull model) {
            ZYCTeachLearningSubmitModel *m = [[ZYCTeachLearningSubmitModel alloc] init];
            m.quSubjectId = model.quSubjectId;
            m.answerContent = model.answerContent;
            m.subjectType = model.subjectType;
            if (self.selectResultArr.count > 0) {
                [self.selectResultArr enumerateObjectsUsingBlock:^(ZYCTeachLearningSubmitModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([m.quSubjectId isEqualToString:obj.quSubjectId]) {
                        [self.selectResultArr removeObject:obj];
                        [self.selectResultArr addObject:m];
                        *stop = NO;
                    }else{
                        [self.selectResultArr addObject:m];
                        *stop = NO;
                        return;
                    }
                }];
            }else{
                [self.selectResultArr addObject:m];
            }
            NSString *filePath = [self createCurrentPaperFilePath];
            BOOL isSuccess =  [NSKeyedArchiver archiveRootObject:self.selectResultArr toFile:filePath];
//               NSLog(@"%@",isSuccess ? @"成功" : @"失败");
        };
        return cell;
    }else{//选择题 (单选/多选)
        ZYCTeachingTeachLearningPaperCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeachingTeachLearningPaperCell class]) forIndexPath:indexPath];
        cell.model = model;
        cell.selectModelBlock = ^(ZYCSubjectModel * _Nonnull model) {
            ZYCTeachLearningSubmitModel *m = [[ZYCTeachLearningSubmitModel alloc] init];
            m.quSubjectId = model.quSubjectId;
            m.items = model.selectAnswer;
            m.subjectType = model.subjectType;
            if (self.selectResultArr.count > 0) {
                [self.selectResultArr enumerateObjectsUsingBlock:^(ZYCTeachLearningSubmitModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([m.quSubjectId isEqualToString:obj.quSubjectId]) {
                        [self.selectResultArr removeObject:obj];
                        [self.selectResultArr addObject:m];
                        *stop = NO;
                    }else{
                        [self.selectResultArr addObject:m];
                        *stop = NO;
                        return;
                    }
                }];
            }else{
                [self.selectResultArr addObject:m];
            }
            NSString *filePath = [self createCurrentPaperFilePath];
            BOOL isSuccess =  [NSKeyedArchiver archiveRootObject:self.selectResultArr toFile:filePath];
//               NSLog(@"%@",isSuccess ? @"成功" : @"失败");
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [UIView new];
    footer.backgroundColor = HEX_RGB(@"#F9F9F9");
    return footer;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [UIView new];
    header.backgroundColor = HEX_RGB(@"#F9F9F9");
    return header;
}


#pragma mark - 网络请求
// 获取详情页面
- (void)loadTeachLearningPaper{
    NSDictionary *params = @{
        @"quEvalutionId":self.quEvalutionId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeachLearningPaper requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                self.paperModel = [ZYCTeachLearningPaperModel yy_modelWithDictionary:responseObject[@"body"]];
                self.headerView.model = self.paperModel;
                for (ZYCSubjectModel *subjectModel  in self.paperModel.subjectVoList) {//所有题目
                    if ([subjectModel.subjectType integerValue] == 3) {//简单题
                        for (ZYCTeachLearningSubmitModel *m in self.localSaveArr) {
                            if ([m.quSubjectId isEqualToString:subjectModel.quSubjectId]) {
                                if (m.answerContent.length > 0){
                                    subjectModel.answerContent = m.answerContent;
                                    subjectModel.isPaper = 1;
                                }else{
                                    subjectModel.isPaper = 0;
                                }
                            }
                        }
                    }else{
                        subjectModel.isPaper = 0;
                        for (ZYCAnswerModel *answerModel in subjectModel.subjectItemVoList) {
                            //所有答案选项
                            answerModel.quSubjectId = subjectModel.quSubjectId;
                            answerModel.subjectType = subjectModel.subjectType;
                            for (ZYCTeachLearningSubmitModel *m in self.localSaveArr) {
                                if ([m.items containsObject:answerModel.subjectItemId]) {
                                    answerModel.checkFlag = 1;
                                    subjectModel.isPaper = 1;
                                }
                            }
                        }
                    }
                }
                // 重新设置
                [self.tableView layoutIfNeeded];
                self.tableView.tableHeaderView = self.headerView;

                [self.tableView reloadData];
            }else if([responseObject[@"code"] integerValue] == kContentRevoke){
                self.tableView.hidden = YES;
                self.revokeView.hidden = NO;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}


// 提交
- (void)clickRightItem:(UIButton *)sender{
    [self uploadAnswer];
}

- (void)uploadAnswer{
    NSArray *isPaperArr = [self.paperModel.subjectVoList valueForKeyPath:@"isPaper"];
    if ([isPaperArr containsObject:@0]) {
        [MrjToast makeToast:@"请选择选项" makeView:self.view];
        return;
    }
    NSMutableArray *resultArr = [NSMutableArray arrayWithCapacity:0];
    for (ZYCTeachLearningSubmitModel *model in self.selectResultArr) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        if ([model.subjectType integerValue] == 3) {
            [dict setObject:self.quEvalutionId forKey:@"quEvalutionId"];
            [dict setObject:model.quSubjectId forKey:@"quSubjectId"];
            [dict setObject:model.answerContent forKey:@"answerContent"];
            [resultArr addObject:dict];
        }else{
            NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];
            for (NSString *item in model.items) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:self.quEvalutionId forKey:@"quEvalutionId"];
                [dict setObject:model.quSubjectId forKey:@"quSubjectId"];
                [dict setObject:item forKey:@"quSubjectItemId"];
                [temp addObject:dict];
            }
            [resultArr addObjectsFromArray:temp];
        }
    }
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultArr options:NSJSONWritingPrettyPrinted  error:&parseError];
    NSString *jsonstr =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSData *objectData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *params = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&parseError];
    
    [MrjSVProgressHUD showWithStatus:@"提交中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AddAnswer requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"body"]];
                [self clean];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

// 提交成功后删除缓存
- (void)clean{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self createCurrentPaperFilePath];
    [fileManager removeItemAtPath:filePath error:nil];
}
    
#pragma mark - getters

- (ZYCMessageRevokeView *)revokeView {
    ZYCWeakSelf
    if (!_revokeView) {
        _revokeView = [[ZYCMessageRevokeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _revokeView.hidden = YES;
        _revokeView.closeBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        [self.navigationController.view addSubview:_revokeView];
    }
    return _revokeView;
}

- (ZYCTeachingTeachLearningDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCTeachingTeachLearningDetailHeaderView alloc] initWithFrame:CGRectZero];
    }
    return _headerView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeachingTeachLearningPaperCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeachingTeachLearningPaperCell class])];
        [_tableView registerClass:[ZYCTeachingTeachLearningPaperContentCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeachingTeachLearningPaperContentCell class])];
        _tableView.estimatedRowHeight = 144.0f;
        _tableView.rowHeight = UITableViewAutomaticDimension;
    }
    return _tableView;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[UIButton alloc] init];
        [_rightButton setTitle:@"提交" forState:UIControlStateNormal];
        [_rightButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}



- (NSMutableArray *)selectResultArr {
    if (!_selectResultArr) {
        _selectResultArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectResultArr;
}


- (NSString *)createCurrentPaperFilePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    ZYCUserLoginModel *userLogin = [ZYCUserLoginModel userLogin];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *userIdDirectryPath = [documentPath stringByAppendingPathComponent:userLogin.userId];
    // 创建文件夹(用户ID)
    [fileManager createDirectoryAtPath:userIdDirectryPath withIntermediateDirectories:YES attributes:nil error:nil];
    // 评价评学路径
    NSString *teachLearningPath = [userIdDirectryPath stringByAppendingPathComponent:@"teachLearning"];
    // 创建文件夹(评价评学)
    [fileManager createDirectoryAtPath:teachLearningPath withIntermediateDirectories:YES attributes:nil error:nil];
    // 试卷ID路径
    NSString *filePath = [teachLearningPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",self.quEvalutionId]];
    return filePath;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
